import React from "react";
import { Table, Space, Button, Modal, Form, Input, message } from "antd";
import type { ColumnsType, TablePaginationConfig } from "antd/es/table";
import type { FilterValue, SorterResult } from "antd/es/table/interface";
import { ColumnType, FilterConfirmProps } from "antd/lib/table/interface";
import { SearchOutlined } from "@ant-design/icons";
import Highlighter from "react-highlight-words";

import { TenantI } from "../../types/system";
import { createTenant, searchTenantList, updateTenant } from "../../api/system";
import styles from "./index.module.less";
import { dayjs } from "../../App";
import { useLocation, useNavigate } from "react-router-dom";
import { useRequest } from "ahooks";

const TenantManage = (): JSX.Element => {
  const location = useLocation();
  const navigate = useNavigate();
  const [showEditModal, setShowEditModal] = React.useState<boolean>(false);
  const [submitting, setSubmitting] = React.useState<boolean>(false);
  const [formDisabled] = React.useState<boolean>(false);
  const [searchText, setSearchText] = React.useState("");
  const [totalCount, setTotalCount] = React.useState<number>(0);
  // const [searchedColumn, setSearchedColumn] = React.useState("");
  // const [loadingTenantList, setLoadingTenantList] = React.useState<boolean>(false);
  const [tenantList, setTenantList] = React.useState<TenantI[]>([]);
  const searchInput = React.useRef<any>(null);
  const [tenantForm] = Form.useForm<TenantI>();
  // const [importForm] = Form.useForm();

  const { loading, run } = useRequest(
    (paramsString: string) => searchTenantList(paramsString),
    {
      manual: false,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp, params) {
        // console.log(params);
        setTenantList(resp.data.data);
        setTotalCount(resp.data.totalCount);
      },
      onError(e, params) {
        message.error("获取数据失败");
      },
    }
  );

  type DataIndex = keyof TenantI;
  const handleSearch = (
    selectedKeys: string[],
    confirm: (param?: FilterConfirmProps) => void,
    dataIndex: DataIndex
  ) => {
    // confirm触发TableChange动作
    setSearchText(selectedKeys[0]);
    // setSearchedColumn(String(dataIndex));
    confirm();
  };

  const handleReset = (clearFilters: () => void) => {
    clearFilters();
  };

  // const handleBeforeUploadFile = (file: File) => {
  // 	return false;
  // };

  const getColumnSearchProps: any = (
    dataIndex: DataIndex
  ): ColumnType<typeof columns> => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
      visible,
    }) => (
      <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0] as any}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() =>
            handleSearch(selectedKeys as string[], confirm, dataIndex)
          }
          style={{ marginBottom: 8, display: "block" }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() =>
              handleSearch(selectedKeys as string[], confirm, dataIndex)
            }
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            搜索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({ closeDropdown: false });
              setSearchText((selectedKeys as string[])[0]);
              // setSearchedColumn(dataIndex);
            }}
          >
            筛选
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              visible = false;
            }}
          >
            关闭
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered: boolean) => (
      <SearchOutlined style={{ color: filtered ? "#1890ff" : undefined }} />
    ),
    onFilter: (value, record: any) => {
      if (!record[dataIndex]) {
        return false;
      } else {
        return record[dataIndex]
          .toString()
          .toLowerCase()
          .includes((value as string).toLowerCase());
      }
    },
    onFilterDropdownOpenChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
    render: (value: any, record: any, index: number): React.ReactNode => {
      if (typeof record[dataIndex.toString().split(".")[0]] === "object") {
        // console.log(record[dataIndex.toString().split(".")[0]]);
        if (record[dataIndex.toString().split(".")[0]]) {
          return (
            <Highlighter
              highlightStyle={{ backgroundColor: "#ffc069", padding: 0 }}
              searchWords={[searchText]}
              autoEscape
              textToHighlight={
                record &&
                record[dataIndex.toString().split(".")[0]] &&
                record[dataIndex.toString().split(".")[0]][
                  dataIndex.toString().split(".")[1]
                ]
                  ? record[dataIndex.toString().split(".")[0]][
                      dataIndex.toString().split(".")[1]
                    ].toString()
                  : ""
              }
            />
          );
        } else {
          return <span></span>;
        }
      } else {
        return (
          <Highlighter
            highlightStyle={{ backgroundColor: "#ffc069", padding: 0 }}
            searchWords={[searchText]}
            autoEscape
            textToHighlight={
              record && record[dataIndex.toString().split(".")[0]]
                ? record[dataIndex.toString().split(".")[0]].toString()
                : ""
            }
          />
        );
      }
    },
  });

  const columns: ColumnsType<TenantI> = [
    {
      title: "中心名称",
      dataIndex: "name",
      width: "200px",
      ellipsis: true,
      key: "name",
      sorter: (a: TenantI, b: TenantI) => {
        return a.name.localeCompare(b.name);
      },
      render: (text) => <span>{text}</span>,
      ...getColumnSearchProps("name"),
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      width: "200px",
      ellipsis: true,
      key: "createdAt",
      sorter: (a: TenantI, b: TenantI) => {
        return dayjs(a.createdAt).valueOf() - dayjs(b.createdAt).valueOf();
      },
      render: (text) => {
        return <span>{dayjs(text).format("YYYY-MM-DD HH:mm:ss")}</span>;
      },
    },
    {
      title: "操作",
      dataIndex: "operation",
      width: "200px",
      ellipsis: true,
      fixed: "right" as const,
      key: "operation",
      render: (_: any, record: TenantI) => (
        <Space>
          <Button
            onClick={handleEditTenantClick.bind(this, record)}
            size="small"
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  const handleEditTenantClick = (record: TenantI) => {
    // console.log(record);
    tenantForm.setFieldsValue(record);
    setShowEditModal(true);
  };

  const handleAddClick = () => {
    tenantForm.resetFields();
    setShowEditModal(true);
  };

  // const handleRoleTenantChange = () => {
  // 	console.log("handleRoleTenantChange");
  // };

  const handleEditModalOk = () => {
    tenantForm
      .validateFields()
      .then((values: any) => {
        // console.log(values);
        setSubmitting(true);
        if (values.id) {
          updateTenant(values).then(
            (res) => {
              // console.log(res);
              tenantForm.resetFields();
              setSubmitting(false);
              setShowEditModal(false);
              // refreshTenantList(location.search);
              run(location.search.replace(/^\?/, ""));
            },
            (err: any) => {
              console.log(err);
              message.error(err.detail);
              setSubmitting(false);
              setShowEditModal(false);
            }
          );
        } else {
          createTenant(values).then(
            (res) => {
              // console.log(res);
              tenantForm.resetFields();
              setSubmitting(false);
              setShowEditModal(false);
              // refreshTenantList(location.search);
              run(location.search.replace(/^\?/, ""));
            },
            (err: any) => {
              console.log(err);
              message.error(err.detail);
              setSubmitting(false);
              setShowEditModal(false);
            }
          );
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };

  const handleEditModalCancel = () => {
    setShowEditModal(false);
  };

  // 表格条件改变时，将表格参数写到URL并根据表格条件重新获取数据
  const handleTableChange = (
    newPagination: TablePaginationConfig,
    newFilters: Record<string, FilterValue | null>,
    newSorters: SorterResult<TenantI> | SorterResult<TenantI>[]
  ) => {
    const params = new URLSearchParams();
    params.set("currentPage", newPagination.current?.toString() || "1");
    params.set("pageSize", newPagination.pageSize?.toString() || "10");

    params.set("filters", JSON.stringify(newFilters));
    params.set("sorters", JSON.stringify(newSorters));

    // console.log(`${location.pathname}?${params.toString()}`);
    navigate(`${location.pathname}?${params.toString()}`);
    // refreshTenantList(params.toString());
    run(params.toString());
  };

  // // 换成useRequest写法
  // const refreshTenantList = React.useCallback((paramsString: string) => {
  // 	setLoadingTenantList(true);
  // 	searchTenantList(paramsString).then(
  // 		(res: any) => {
  // 			console.log(res);
  // 			setTenantList(res.data.data);
  // 			// setTotalCount(res.data.totalCount);
  // 			setLoadingTenantList(false);
  // 		},
  // 		(err: any) => {
  // 			console.log(err);
  // 			message.error(err.detail);
  // 			setLoadingTenantList(false);
  // 		}
  // 	);
  // }, []);

  // 换成useRequest写法
  // React.useEffect(() => {
  // 	// console.log(location);
  // 	// 获取URL中的参数
  // 	// const urlSearchParams = new URLSearchParams(location.search);
  // 	// console.log(urlSearchParams);
  // 	refreshTenantList(location.search.replace(/^\?/, ""));
  // }, [location, refreshTenantList]);

  return (
    <div className={styles.table}>
      <div>
        <div className={styles.tableHeader}>
          <Space style={{ marginBottom: 16 }}>
            <Button onClick={handleAddClick} size="small">
              添加
            </Button>
          </Space>
        </div>
        <Table
          columns={columns}
          rowKey={(record: TenantI) => record.id}
          dataSource={tenantList}
          expandable={{
            defaultExpandedRowKeys: ["0"],
          }}
          pagination={{
            total: totalCount,
          }}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 800, y: 600 }}
        ></Table>
      </div>
      <Modal
        title={tenantForm.getFieldValue("id") ? "修改中心" : "添加中心"}
        open={showEditModal}
        onOk={handleEditModalOk}
        onCancel={handleEditModalCancel}
        confirmLoading={submitting}
      >
        <Form
          form={tenantForm}
          layout="vertical"
          name={"tenantForm"}
          autoComplete="off"
          disabled={formDisabled}
        >
          <Form.Item
            name="id"
            label="id"
            hidden={!tenantForm.getFieldValue("id")}
            rules={[
              {
                required: false,
                message: "请输入id",
              },
            ]}
          >
            <Input disabled={true} />
          </Form.Item>
          <Form.Item
            name="name"
            label="中心名称"
            hasFeedback
            rules={[
              {
                required: true,
                message: "请输入中心名称",
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TenantManage;
